package com.tao.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mysql.cj.util.StringUtils;
import com.tao.gulimall.product.entity.CategoryBrandRelationEntity;
import com.tao.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tao.common.utils.PageUtils;
import com.tao.common.utils.Query;

import com.tao.gulimall.product.dao.BrandDao;
import com.tao.gulimall.product.entity.BrandEntity;
import com.tao.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // key 可能作为品牌名称，也可能作为品牌id
        String key = params.get("key").toString();
        LambdaQueryWrapper<BrandEntity> lqw = new LambdaQueryWrapper<>();
        if(!StringUtils.isNullOrEmpty(key)){
            lqw.eq(BrandEntity::getBrandId,key).or().like(BrandEntity::getName,key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                lqw
        );
        return new PageUtils(page);
    }

    /**
     * 更新品牌同时更新其他信息
     * @param brand
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateWithRelation(BrandEntity brand) {
        // 品牌更新
        this.updateById(brand);

        //  更新了品牌名称等信息
        if(!StringUtils.isNullOrEmpty(brand.getName())){
            //同步更新关联的
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());

            // TODO 更新其他关联
        }


    }

}